/*
 * @Author: your name
 * @Date: 2021-12-01 10:22:19
 * @LastEditTime: 2021-12-01 17:31:53
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /my_calendar/src/components/calendar/components/body.js
 */
import moment from 'moment'
import dateFunc from './dateFunc'

export default {
  props: {
    currentDate: {},
    events: {
      type: Array,
      default: () => []
    },
    weekNames: {
      type: Array,
      default: () => []
    },
    monthNames: {},
    firstDay: {
      type: [String, Number],
      default: 0
    }
  },
  created () {
    // this.events.forEach((item, index) => {
    //   item._id = item.id || index
    //   item.end = item.end || item.start
    // })
    // this.events = events
  },
  data () {
    return {
      rowMaxDataLength: [], // 没行最大数据长度
      viewAllCalendar: [], // 当前视图所有天数
      calendarRenderViewFirstDay: null,
      calendarRenderViewLastDay: null,
      // weekNames : DAY_NAMES,
      weekMask: [1, 2, 3, 4, 5, 6, 7],
      // events : [],
      isLismit: true,
      eventLimit: 3,
      showMore: false,
      morePos: {
        top: 0,
        left: 0
      },
      selectDay: {}
    }
  },
  watch: {
    weekNames (val) {
      console.log('watch weekNames', val)
    }
  },
  computed: {
    currentDates () {
      return this.getCalendar()
    }
  },
  methods: {
    isBegin (event, date, index) {
      const st = new Date(event.start)
      if (index === 0 || st.toDateString() === date.toDateString()) {
        return event.title
      }
      return '　'
    },
    moreTitle (date) {
      const dt = new Date(date)
      return (
        this.weekNames[dt.getDay()] +
        ', ' +
        this.monthNames[dt.getMonth()] +
        dt.getDate()
      )
    },
    classNames (cssClass) {
      if (!cssClass) return ''
      // string
      if (typeof cssClass === 'string') return cssClass

      // Array
      if (Array.isArray(cssClass)) return cssClass.join(' ')

      // else
      return ''
    },
    getCalendar () {
      // calculate 2d-array of each month
      // first day of this month
      const now = new Date() // today
      const current = new Date(this.currentDate)
      const startDate = dateFunc.getStartDate(current) // 1st day of this month
      const curWeekDay = startDate.getDay()
      // begin date of this table may be some day of last month
      let diff = parseInt(this.firstDay) - curWeekDay
      diff = diff > 0 ? diff - 7 : diff
      // 视图渲染到第一天 毫秒时间戳
      const calendarRenderViewFirstDay = startDate.setDate(
        startDate.getDate() + diff
      )
      const timeObj = new Date(calendarRenderViewFirstDay)
      this.calendarRenderViewFirstDay = `${timeObj.getFullYear()}-${(timeObj.getMonth() + 1).toString().padStart(2, 0)}-${timeObj.getDate().toString().padStart(2, 0)}`
      const calendar = []
      const viewAllCalendar = []
      for (let perWeek = 0; perWeek < 6; perWeek++) {
        const week = []
        for (let perDay = 0; perDay < 7; perDay++) {
          viewAllCalendar.push(moment(startDate).format('YYYYMMDD'))
          week.push({
            monthDay: startDate.getDate(),
            isToday: now.toDateString() === startDate.toDateString(),
            isCurMonth: startDate.getMonth() === current.getMonth(),
            weekDay: perDay,
            date: new Date(startDate),
            events: this.slotEvents(startDate)
          })
          startDate.setDate(startDate.getDate() + 1)
        }
        calendar.push(week)
      }
      const calendarRenderViewLastDay = startDate.setDate(
        startDate.getDate() - 1
      )
      const lastTimeObj = new Date(calendarRenderViewLastDay)
      this.calendarRenderViewLastDay = `${lastTimeObj.getFullYear()}-${(lastTimeObj.getMonth() + 1).toString().padStart(2, 0)}-${lastTimeObj.getDate().toString().padStart(2, 0)}`
      const dataFormat = dateFunc.formatEventsInHashTable(this.events, this.firstDay, 7, this.calendarRenderViewFirstDay, this.calendarRenderViewLastDay)
      this.viewAllCalendar = viewAllCalendar
      this.formatDayData(dataFormat, this.calendarRenderViewFirstDay)
      return calendar
    },

    formatDayData (hastdata, startdate) {
      console.log('hastdata: ', this.viewAllCalendar)
      var B = []
      var b = []
      for (var j = 0; j < 6; j++) {
        var k = 0
        b = []
        for (var i = 0; i < 7; i++) {
          var newkeyDate = dateFunc.DateAdd('d', j * 7 + i, startdate)
          var newkey = dateFunc.dateFormat(newkeyDate, 'yyyyMMdd')
          b[i] = hastdata[newkey]
          if (b[i] && b[i].length > 0 && b[i].length > k) {
            k = b[i].length
          }
        }
        B[j] = k
      }
      this.rowMaxDataLength = B
      console.log('B ', B)
    },
    slotEvents (date) {
      // find all events start from this date
      const thisDayEvents = this.events.filter((day) => {
        const dt = new Date(day.start)
        const st = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate())
        const ed = day.end ? new Date(day.end) : st
        return date >= st && date <= ed
      })

      // sort by duration
      thisDayEvents.sort((a, b) => {
        if (!a.cellIndex) return 1
        if (!b.cellIndex) return -1
        return a.cellIndex - b.cellIndex
      })

      // mark cellIndex and place holder
      for (let i = 0; i < thisDayEvents.length; i++) {
        thisDayEvents[i].cellIndex = thisDayEvents[i].cellIndex || i + 1
        thisDayEvents[i].isShow = true
        if (thisDayEvents[i].cellIndex === i + 1 || i > 2) continue
        thisDayEvents.splice(i, 0, {
          title: 'holder',
          cellIndex: i + 1,
          start: dateFunc.format(date, 'yyyy-MM-dd'),
          end: dateFunc.format(date, 'yyyy-MM-dd'),
          isShow: false
        })
      }

      return thisDayEvents
    },
    isStart (eventDate, date) {
      const st = new Date(eventDate)
      return st.toDateString() === date.toDateString()
    },
    isEnd (eventDate, date) {
      const ed = new Date(eventDate)
      return ed.toDateString() === date.toDateString()
    },
    selectThisDay (day, jsEvent) {
      this.selectDay = day
      this.showMore = true
      this.morePos = this.computePos(event.target)
      this.morePos.top -= 100
      const events = day.events.filter((item) => {
        return item.isShow === true
      })
      this.$emit('moreclick', day.date, events, jsEvent)
    },
    computePos (target) {
      const eventRect = target.getBoundingClientRect()
      const pageRect = this.$refs.dates.getBoundingClientRect()
      return {
        left: eventRect.left - pageRect.left,
        top: eventRect.top + eventRect.height - pageRect.top
      }
    },
    dayClick (day, jsEvent) {
      this.$emit('dayclick', day, jsEvent)
    },
    eventClick (event, jsEvent) {
      if (!event.isShow) {
        return
      }
      jsEvent.stopPropagation()
      const pos = this.computePos(jsEvent.target)
      this.$emit('eventclick', event, jsEvent, pos)
    }
  }
}
